import fui from "../../lib/fui.js";
import game from "./game.js";

const Consts = {
    PC_PAGEWIDTH_RATE: 0.56,
    template_pbox: fui.$("ux-template#pbox").html(),
}

function game_area(dom, io_fns) {
    const dom_pboxs = []
    for (const row of R.range(1, 16)) {
        for (const col of R.range(1, 16)) {
            const html = Consts.template_pbox.replace("[ROW]", row).replace("[COL]", col)
            dom.append(html)
            dom_pboxs.push(dom.children().last())
        }
    }
    $(".pbox").on("click", function(e){
        const dom = fui.$(e.target)
        const y = Number(dom.css("grid-row").split(' ')[0]) - 1
        const x = Number(dom.css("grid-column").split(' ')[0]) - 1
        const loc = y * 15 + x
        io_fns.on_down(loc)
    })
    return (fs)=>{
        const rtop = io_fns.get_record_top()
        const board = io_fns.get_board()
        board.foreach((loc,p)=>{
            const dom = dom_pboxs[loc]
            if (p == game.PIECE_BLACK) {
                if (! dom.hasClass("pbox-black")) {dom.removeClass("pbox-white").addClass("pbox-black")}
            } else if (p == game.PIECE_WHITE) {
                if (! dom.hasClass("pbox-white")) {dom.removeClass("pbox-black").addClass("pbox-white")}
            } else if (dom.hasClass("pbox-black") || dom.hasClass("pbox-white")) {
                dom.removeClass("pbox-black").removeClass("pbox-white")
            }
            if (rtop.loc() == loc) {
                dom.html(String(rtop.step()))
            } else if (dom.html().length > 0) {
                dom.html("")
            }
        })
    }
}

function status(dom, io_fns) {
    const symbol_black = "●"
    const symbol_white = "○"
    const frame_game_info = fui.Label(dom.find("#game-info"), {
        on_frame(widget){
            let black_str = "Player"
            let white_str = "Player"
            if (io_fns.ai_player(game.PIECE_BLACK)) {
                black_str = "AI"
            }
            if (io_fns.ai_player(game.PIECE_WHITE)) {
                white_str = "AI"
            }
            widget.update(`${symbol_black}${black_str} vs ${symbol_white}${white_str}`)
        }
    })

    const frame_game_status = fui.Label(dom.find("#game-status"), {
        on_frame(widget){
            const board = io_fns.get_board()
            const count_str = `${symbol_black} ${board.n_black()} | ${symbol_white} ${board.n_white()}`
            let pcur_str = (io_fns.get_pcur() == game.PIECE_BLACK) ? `→${symbol_black}` : `→${symbol_white}`
            const end_piece = io_fns.get_end_piece()
            if (end_piece < game.PIECE_EMPTY){
                pcur_str = "DRAW"
            } else if (end_piece == game.PIECE_BLACK) {
                pcur_str = `${symbol_black}WIN`
            } else if (end_piece == game.PIECE_WHITE) {
                pcur_str = `${symbol_white}WIN`
            }
            const n_str = `${Math.min(game.BOARD_LEN, board.n_piece() + 1)}`
            widget.update(`${n_str} ${pcur_str} (${count_str})`)
        }
    })
    const frame_ai_status = fui.Label(dom.find("#ai-status"), {
        on_frame(widget){
            let ai_pcur = io_fns.ai_player(game.PIECE_BLACK) ? game.PIECE_BLACK : (io_fns.ai_player(game.PIECE_WHITE) ? game.PIECE_WHITE : game.PIECE_EMPTY)
            if (io_fns.ai_player(game.PIECE_BLACK) && io_fns.ai_player(game.PIECE_WHITE)) {
                ai_pcur = io_fns.get_pcur()
            }
            let status_str = "IDLE"
            let pcur_str = ""
            if ((ai_pcur != game.PIECE_EMPTY) && (! io_fns.ai_player(game.piece_side(ai_pcur)))) {
                pcur_str = (ai_pcur == game.PIECE_BLACK) ? `:${symbol_black}` : `:${symbol_white}`
                const say = io_fns.get_ai_said(ai_pcur)
                if (say.length > 0) {
                    pcur_str = `${pcur_str} <div class="say">${say}</div>`
                }
            }
            const status = io_fns.get_ai_status(ai_pcur)
            if (status.length > 0) {status_str = status}
            widget.update(`[AI${pcur_str}] ${status_str}`)
        },
    })
    return (_)=>{
        frame_game_info()
        frame_game_status()
        frame_ai_status()
    }
}

function tools(dom, io_fns) {
    fui.Select(dom.find("#sel-uct-times"), {
        on_init(widget){
            widget.select_with_eq(io_fns.param("uct-times"))
        },
        on_select(_dom_option, ux_value, _sel){
            io_fns.param("uct-times", ux_value)
        },
    })
    fui.Select(dom.find("#sel-extra"), {
        on_init(widget){
            widget.select_with_eq(io_fns.param("level"))
        },
        on_select(dom_option, ux_value, sel){
            const param = dom_option.attr("param")
            if (param == "level") {
                io_fns.param("level", ux_value)
            } else {
                io_fns.on_extra(ux_value)
                sel.select_with_eq(io_fns.param("level"))
            }
        },
    })
    fui.PushButton(dom.find("#cmd-reset"), ()=>{io_fns.on_cmd_reset()})
    fui.PushButton(dom.find("#cmd-load-first"), ()=>{io_fns.on_cmd_load_first()})
    fui.PushButton(dom.find("#cmd-load-last"), ()=>{io_fns.on_cmd_load_last()})
    fui.PushButton(dom.find("#cmd-undo"), ()=>{io_fns.on_cmd_undo()})
    fui.PushButton(dom.find("#cmd-redo"), ()=>{io_fns.on_cmd_redo()})
    const use_ai_black = fui.CheckBox(dom.find("#use-ai-black"), {
        on_change(widget){
            io_fns.ai_player(game.PIECE_BLACK, widget.is_checked())
        },
        on_frame(widget){
            if (widget.is_checked() != io_fns.ai_player(game.PIECE_BLACK)) {
                widget.checked(io_fns.ai_player(game.PIECE_BLACK))
            }
        },
    })
    const use_ai_white = fui.CheckBox(dom.find("#use-ai-white"), {
        on_change(widget){
            io_fns.ai_player(game.PIECE_WHITE, widget.is_checked())
        },
        on_frame(widget){
            if (widget.is_checked() != io_fns.ai_player(game.PIECE_WHITE)) {
                widget.checked(io_fns.ai_player(game.PIECE_WHITE))
            }
        },
    })
    return (_)=>{
       use_ai_black()
       use_ai_white()
    }
}

function fix_wtf_the_layout(amw) {
    if ("pc" == amw) {
        const fuck_w = "3.1dvh"
        fui.$(".pbox").css("width", fuck_w).css("height", fuck_w).css("line-height", fuck_w)
    }
    fui.$("body").show()
}
function init(io_fns) {
    const amw = fui.adaption_mobile_width(Consts.PC_PAGEWIDTH_RATE)
    const fs = new fui.FrameSystem()
    fs.frame_join(status(fui.$("#head"), io_fns))
    fs.frame_join(game_area(fui.$("#area"), io_fns))
    fs.frame_join(tools(fui.$("#bottom"), io_fns))
    fix_wtf_the_layout(amw)
    return ()=>{fs.on_frame()}
}

export default {
    init,
}
